#!/bin/bash

BINDIR=$(cd $(dirname $0) && pwd)

. ${BINDIR}/common
. ${BINDIR}/functions

if [ "x$1" = "x" ] || [ "x$2" = "x" ] || [ "x$3" = "x" ]
then
	echo "USAGE: $0 PLUGINNAME GITURL BRANCH SHA1"
	exit 1
fi

teeOutput

echo "Installing plugin $1"
cd ${PLUGINDIR} && $SUDO git clone --single-branch --branch $3 $2 $1
rc=$?
if [ $rc -ne 0 ]; then
	echo "Failed to fetch $1 using $2 -- aborting"
	exit 1
fi

if [ "x$4" != "x" ]
then
	(cd $1 && $SUDO git reset --hard $4)
fi


$SUDO chown -R fpp.fpp $1

if [ -x "${PLUGINDIR}/$1/scripts/fpp_install.sh" ]
then
	echo "Running fpp_install.sh script for $1"
	$SUDO ${PLUGINDIR}/$1/scripts/fpp_install.sh
else
	if [ -x "${PLUGINDIR}/$1/fpp_install.sh" ]
	then
		echo "Running fpp_install.sh script for $1"
		$SUDO ${PLUGINDIR}/$1/fpp_install.sh
	fi
fi
